//@Auth:zdl
//通讯协议处理，主要处理封包和解包的过程
package protocol

import (
	"bytes"
	"encoding/binary"
	"fmt"
	"github.com/gogf/gf/g/os/glog"
)

const (
	ConstHeader         = "www.01happy.com"
	ConstHeaderLength   = 15
	ConstSaveDataLength = 4
)

//封包
func Packet(message []byte) []byte {
	return append(append([]byte(ConstHeader), IntToBytes(len(message))...), message...)
}

func PacketString(message string)([]byte,error){
	buf:=bytes.NewBufferString(message)
	bytes:=make([]byte,3000)
	n,err:=buf.Read(bytes)
	glog.Debug("n============",n)
	if err!=nil {
		return bytes,err
	}
	return bytes,nil
}

type ModelStc struct {
	ConstHeader         []byte
	ConstHeaderLength   int
	ConstSaveDataLength int
}
var stc ModelStc
func MultiUnpack(channel string){

	switch channel {
	case "eb90":
		stc=ModelStc{
			ConstHeader:[]byte{0xeb, 0x90, 0xeb,0x90, 0xeb, 0x90},
			ConstHeaderLength:6,
			ConstSaveDataLength:1,
		}
	}
}

func init(){
	MultiUnpack("eb90")
}

//解包
func Unpack(buffer []byte, readerChannel chan []byte) []byte {
	length := len(buffer)
	var i int
	for i = 0; i < length; i = i + 1 {
		if length < i+stc.ConstHeaderLength+stc.ConstSaveDataLength {
			break
		}
		if bytes.Equal(buffer[i:i+stc.ConstHeaderLength],stc.ConstHeader) {
			//fmt.Println("buffer====",buffer)
			fmt.Println("i+stc.ConstHeaderLength==========",i+stc.ConstHeaderLength,"    =====",i+stc.ConstHeaderLength+stc.ConstSaveDataLength)
			messageLength := int(buffer[i+stc.ConstHeaderLength : i+stc.ConstHeaderLength+stc.ConstSaveDataLength][0])
			fmt.Println("stc.ConstHeaderLength+stc.ConstSaveDataLength]=====",buffer[i+stc.ConstHeaderLength : i+stc.ConstHeaderLength+stc.ConstSaveDataLength])
			fmt.Println("messageLength=============",messageLength)
			if length < i+stc.ConstHeaderLength+stc.ConstSaveDataLength+messageLength {
				break
			}
			data := buffer[i+stc.ConstHeaderLength+stc.ConstSaveDataLength : i+stc.ConstHeaderLength+stc.ConstSaveDataLength+messageLength]
			if len(data)==0{
				break
			}
			readerChannel <- data

			i += stc.ConstHeaderLength +stc.ConstSaveDataLength + messageLength - 1
		}
	}

	if i == length {
		return make([]byte, 0)
	}
	return buffer[i:]
}

//整形转换成字节
func IntToBytes(n int) []byte {
	x := int32(n)
	bytesBuffer := bytes.NewBuffer([]byte{})
	binary.Write(bytesBuffer, binary.BigEndian, x)
	return bytesBuffer.Bytes()
}

//字节转换成整形
func BytesToInt(b []byte) int {
	bytesBuffer := bytes.NewBuffer(b)
	var x int8
	binary.Read(bytesBuffer, binary.BigEndian, &x)
	return int(x)
}


//2字节转换成整型
func BytesToUInt16(b []byte) int {
	bytesBuffer := bytes.NewBuffer(b)

	var x uint16
	binary.Read(bytesBuffer, binary.LittleEndian, &x)

	return int(x)
}